package com.taotao.common.service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class RedisService {
	
	@Autowired
	private StringRedisTemplate redisTemple;
	
	@Resource(name="stringRedisTemplate")
	private ValueOperations<String, String> valueOperations;
	
	private static final ObjectMapper mapper = new ObjectMapper();
	
	//执行set指令
	public void set(String key,Object value) throws JsonProcessingException{
		if (!(value instanceof String)) {
			value = mapper.writeValueAsString(value);
		}
		this.valueOperations.set(key, (String)value);
	}
	
	//执行set指令,设置生存时间
	public void set(String key,Object value,Long seconds) throws JsonProcessingException {
		if (!(value instanceof String)) {
			value = mapper.writeValueAsString(value);
		}
		this.valueOperations.set(key, (String)value, seconds, TimeUnit.SECONDS);
		
	}
	
	//执行get指令
	public <T> T get(String key,TypeReference<T> type) throws JsonParseException, JsonMappingException, IOException {
		String json = valueOperations.get(key);
		if (StringUtils.isEmpty(json)) {
			return null;
		}
		if (type == null) {
			return (T)json;
		}
		return mapper.readValue(json, type);
	}
	
	//执行del指令
	public void del(String key){
		this.redisTemple.delete(key);
	}
	
	//设置过期时间
	public void expire(String key,Long seconds){
		this.redisTemple.expire(key, seconds, TimeUnit.SECONDS);
	}
	
	
	

}
